package com.open.demo.api;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.HashMap;

import cz.msebera.android.httpclient.Header;

/**
 */
public class AsyncHttpRequst implements HttpRequestUse {
    @Override
    public void get(final String url, final HashMap<String, Object> params, final HttpCallBack cb) {
        AsyncHttpClient client = new AsyncHttpClient();
        // 设置参数.
        RequestParams requestParams = new RequestParams();
        if (params != null) {
            for (String key : params.keySet()) {
                requestParams.put(key, params.get(key));
            }
        }
        //
        client.get(url, requestParams, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                cb.onSuccess(new String(responseBody));
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                cb.onFailure(statusCode, error.getMessage());
            }
        });
    }

    @Override
    public void post(final String url, final HashMap<String, Object> params, final HttpCallBack cb) {
        AsyncHttpClient client = new AsyncHttpClient();
        // 设置参数.
        RequestParams requestParams = new RequestParams();
        if (params != null) {
            for (String key : params.keySet()) {
                requestParams.put(key, params.get(key));
            }
        }
        //
        client.post(url, requestParams, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                cb.onSuccess(new String(responseBody));
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                cb.onFailure(statusCode, error.getMessage());
            }
        });
    }
}
